package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderQueryService;
import com.cskaoyan.order.utils.ExceptionProcessorUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 创建日期: 2022/04/22 23:11
 *
 * @author ChengWenqi
 */

@Slf4j
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderConverter orderConverter;

    // todo:事务
    @Override
    public OrderListResponse orderList(OrderListRequest request) {
        OrderListResponse response = new OrderListResponse();

        try {
            // 参数校验
            request.requestCheck();
            // 开启分页
            PageHelper.startPage(request.getPage(), request.getSize());

            // 查询该用户id对应的所有order记录
            Example orderExample = new Example(Order.class);
            // todo:参考项目没传sort进来，先按创建时间降序
            orderExample.setOrderByClause(request.getSort());

            Example.Criteria criteria = orderExample.createCriteria();
            criteria.andEqualTo("userId", request.getUserId());
            List<Order> orderList = orderMapper.selectByExample(orderExample);
            // 获取total（所有记录数）
            PageInfo<Order> pageInfo = new PageInfo<>(orderList);
            Long total = pageInfo.getTotal();
            // 将 orderList 转换成 OrderDetailInfoList
            List<OrderDetailInfo> orderDetailList = orderConverter.orderList2DetailList(orderList);

            // 如果查出来的订单数量大于0，再根据 orderId 查询每个订单的 order_item 和 order_shipping
            if (!CollectionUtils.isEmpty(orderDetailList)) {
                for (OrderDetailInfo orderDetail : orderDetailList) {
                    String orderId = orderDetail.getOrderId();
                    // 查询并转换 orderItemDto
                    List<OrderItem> orderItemList = orderItemMapper.queryByOrderId(orderId);
                    List<OrderItemDto> orderItemDtoList = orderConverter.item2dto(orderItemList);
                    orderDetail.setOrderItemDto(orderItemDtoList);

                    // 查询并转换 orderShippingDto
                    OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);
                    OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                    orderDetail.setOrderShippingDto(orderShippingDto);
                }
            }

            response.setTotal(total);
            response.setDetailInfoList(orderDetailList);
            // 设置成功响应码和信息
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderList occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }

    // todo:事务
    @Override
    public OrderDetailResponse orderDetail(OrderDetailRequest request) {
        OrderDetailResponse response = new OrderDetailResponse();

        try {
            // 参数校验
            request.requestCheck();

            String orderId = request.getOrderId();
            // 根据 orderId 查询订单记录
            Order order = orderMapper.selectByPrimaryKey(orderId);
            // 根据 orderId 查询商品明细
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
            // 根据 orderId 查询物流信息
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);

            // 转换成 response 和里面的 dto
            response = orderConverter.order2res(order);
            response.setOrderItemDto(orderConverter.item2dto(orderItems));
            response.setOrderShippingDto(orderConverter.shipping2dto(orderShipping));
            // 设置成功响应码和信息
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderList occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }
}
